package com.sigmatrix.h5.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.dao.OutStorageTerminalUserDao;
import com.sigmatrix.h5.dao.impl.common.impl.BaseDaoImpl;
import com.sigmatrix.h5.entity.OutStorageTerminalUser;
import com.sigmatrix.h5.exception.DaoException;
/**
 * 
 *@ClassName: OutStorageTerminalUserDaoImpl
 *@Description:出库单绑定用户接口实现
 *@author gaomingkai
 *@date 2017年11月22日 下午4:29:08
 */
@Repository(value = "outStorageTerminalUserDao")
public class OutStorageTerminalUserDaoImpl  extends BaseDaoImpl<OutStorageTerminalUser> implements OutStorageTerminalUserDao  {
	
	private static final String TABLE_NAME = "_dealers_out_storage_terminal_user";
	private static final Logger LOGGER = LoggerFactory.getLogger(OutStorageTerminalUserDaoImpl.class);
	
	
	@Override
	public int save(OutStorageTerminalUser obj, String enterpriseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder()
				.append("INSERT INTO ")
				.append(getTname(enterpriseCode, TABLE_NAME))
				.append("(_out_storage_id, _terminal_user_id) ")
				.append("VALUES (?, ?)");
		final Object[] params = new Object[] { 
				obj.getOutStorageId(),obj.getTerminalUserId()
				};
		LOGGER.info(sql.toString());
		LOGGER.info(JSONObject.toJSONString(params));
		final KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
				final PreparedStatement pstmt = con.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
				int index = 1;
				for (final Object value : params) {
					pstmt.setObject(index, value);
					index++;
				}
				return pstmt;
			}
		}, keyHolder);
		return keyHolder.getKey().intValue();
	}

}
